﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Extensions for SPFeatureCollection
	/// </summary>
	public static class SPFeatureCollectionExtensions
	{
		/// <summary>
		/// Checks if a feature has been activated
		/// </summary>
		/// <param name="features"></param>
		/// <param name="name">Name of feature</param>
		/// <returns>True if it was activated</returns>
		public static bool IsActivated(this SPFeatureCollection features, string name)
		{
			SPFeature f = features.FindByName(name);
			
			return (f != null);
		}
		/// <summary>
		/// Finds the feature with the specified name
		/// </summary>
		/// <param name="features"></param>
		/// <param name="name"></param>
		/// <returns>A reference to the feature if found</returns>
		public static SPFeature FindByName(this SPFeatureCollection features, string name)
		{
			if (features == null) throw new ArgumentNullException("features");
			if (string.IsNullOrEmpty(name) == true) throw new ArgumentNullException("name");

			SPFeatureDefinition def = SPFarm.Local.FeatureDefinitions[name];
			if (def == null) throw new ArgumentOutOfRangeException("name");

			return features[def.Id];
		}
		/// <summary>
		/// Deactivates the feature with the specified name
		/// </summary>
		/// <param name="features"></param>
		/// <param name="name">Name of feature to deactivate</param>
		public static void Deactivate(this SPFeatureCollection features, string name)
		{
			SPFeature f = features.FindByName(name);
			if (f != null)
			{
				features.Remove(f.DefinitionId);
			}
		}
	}
}
